package cn.com.woxitech.dev.controller.api;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import cn.com.woxitech.dev.common.APIResult;
import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.CodeUtils;
import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.EncryptionUtils;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.QiniuPhotoUploadUtils;
import cn.com.woxitech.dev.common.SMSCodeUtils;
import cn.com.woxitech.dev.common.StrUtils;
import cn.com.woxitech.dev.model.Lecture;
import cn.com.woxitech.dev.model.QiniuUploadResult;
import cn.com.woxitech.dev.model.RoomManager;
import cn.com.woxitech.dev.model.WmChathistoryFetch;
import cn.com.woxitech.dev.model.gen.WeixinApiAccessToken;
import cn.com.woxitech.dev.model.gen.WmApp;
import cn.com.woxitech.dev.model.gen.WmCatalog;
import cn.com.woxitech.dev.model.gen.WmLecture;
import cn.com.woxitech.dev.model.gen.WmLecturePage;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.PrivilegeService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.SettingService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;

@RestController
@RequestMapping("/luyan")
public class WeixinLUYANController {
	@Autowired
	WeixinService weixinService;
	@Autowired
	SettingService settingService;
	@Autowired
	PrivilegeService privilegeService;
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;
	@Autowired
	AppService appService;
	@Autowired
	private Environment env;

	@RequestMapping(value="/wx/userinfo",method=RequestMethod.POST)
	public Object wx_userinfo(@RequestBody String body) {
		Map<String, Object> mp = new HashMap<String, Object>();
		JsonNode jsonNode;
		try {
			jsonNode = JSONUtils.toJson(body);
			
			String code = jsonNode.get("code").asText();
			String appid = Const.APPID;
			WeixinApiAccessToken waat = weixinService.getApiAccessTokenByAppId(appid);
			WmUser user = weixinService.getWeiXinUserAccessToken(code, waat);
			Date now = new Date(System.currentTimeMillis());
			if(user == null){
				
				return APIResultFactory.fail();
			}else{
				String useruuid = "";
				String name = "";
				String headimgurl = "";
				WmUser targetuser = this.userService.getUserByUnionId(user.getWxUnionid());
				if(targetuser == null){
					//创建这个新用户，并返回useruuid
					useruuid = UUID.randomUUID().toString();
					
					WmUser newuser = new WmUser();
					
					newuser.setCreatetime(now);
					newuser.setLastlogin(now);
					newuser.setUuid(useruuid);
					
//					wu.setuAccessToken(_resp.getString("access_token"));
//					wu.setuExpiresIn(_resp.getInt("expires_in"));
//					wu.setuRefreshToken(_resp.getString("refresh_token"));
//					wu.setWxOpenid(_resp.getString("openid"));
//					wu.setuScope(_resp.getString("scope"));
//					if(_resp.has("unionid")){
					
					newuser.setuAccessToken(user.getuAccessToken());
					newuser.setuExpiresIn(user.getuExpiresIn());
					newuser.setuRefreshToken(user.getuRefreshToken());
					newuser.setWxOpenid(user.getWxOpenid());
					newuser.setuScope(user.getuScope());
					newuser.setWxUnionid(user.getWxUnionid());
					
					
					WmUser newuser2 = this.weixinService.getUserInfoFromWeiXin(user);
//					wu.setLastlogin(new Date(System.currentTimeMillis()));
//					wu.setName(resp_json.get("nickname").textValue());
//					wu.setWxCity(resp_json.get("city").textValue());
//					wu.setWxProvince(resp_json.get("province").textValue());
//					wu.setWxCountry(resp_json.get("country").textValue());
//					wu.setWxHeadimgurl(resp_json.get("headimgurl").textValue());
//					wu.setWxNickname(resp_json.get("nickname").textValue());
//					wu.setWxOpenid(resp_json.get("openid").textValue());
////					wu.setWxPrivilege(wxPrivilege);
//					wu.setWxSex(resp_json.get("sex").textValue());
					
					newuser.setName(newuser2.getName());
					newuser.setWxCity(newuser2.getWxCity());
					newuser.setWxProvince(newuser2.getWxProvince());
					newuser.setWxCountry(newuser2.getWxProvince());
					newuser.setWxHeadimgurl(newuser2.getWxHeadimgurl());
					newuser.setWxNickname(newuser2.getWxNickname());
					newuser.setWxOpenid(newuser2.getWxOpenid());
					newuser.setWxPrivilege(newuser2.getWxPrivilege());
					newuser.setWxSex(newuser2.getWxSex());
					
					this.userService.insertUser(newuser);
					
				}else{
					//更新这个用户，并返回这个用户
					useruuid = targetuser.getUuid();
					
					
					targetuser.setLastlogin(now);
					targetuser.setuAccessToken(user.getuAccessToken());
					targetuser.setuExpiresIn(user.getuExpiresIn());
					targetuser.setuRefreshToken(user.getuRefreshToken());
					targetuser.setWxOpenid(user.getWxOpenid());
					targetuser.setuScope(user.getuScope());
					targetuser.setWxUnionid(user.getWxUnionid());
					
					name = targetuser.getName();
					headimgurl = targetuser.getWxHeadimgurl();
					
					this.userService.updateUser(targetuser);
				}

				
				
				
				mp.put("useruuid", useruuid);
				mp.put("username", name);
				mp.put("headimgurl", headimgurl);
				return APIResultFactory.success(mp);
				
			}
			
			
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return APIResultFactory.success();
		
		
	}

}
